package com.javaDemo.ti;

/**
 * @ClassName: Zifuxiangchen
 * @Auther: csy https://leetcode-cn.com/problems/multiply-strings/solution/can-zhao-xi-tong-ti-jie-de-fang-fa-yi-ji-dlu1/
 * @Date: 2021/6/30 14:23
 * @Description:
 */
public class Zifuxiangchen {
    public static void main(String[] args) {
        String a="123";
        String b="12";
        String c=multiply(a,b);
        System.out.println();
    }
        public static String multiply(String num1, String num2) {
            // 有乘数为0，输出0（避免最后输出的是"0000"这种），字符串的比较要用equals
            if (num1.equals("0")|| num2.equals("0")){
                return "0";
            }

            int index1 = num1.length() - 1;
            String ans = "0";
            while (index1 >= 0){
                StringBuilder sb = new StringBuilder();
                int carry = 0;
                for (int k = num1.length() - 1; k > index1; k--){
                    sb.append(0);
                }
                int index2 = num2.length() - 1;
                while (index2 >= 0){
                    int num1_Int = num1.charAt(index1) - '0';
                    int num2_Int = num2.charAt(index2) - '0';
                    int temp = (num1_Int * num2_Int) + carry;
                    carry = temp / 10;
                    sb.append(temp % 10);
                    index2--;
                }
                if (carry > 0){
                    sb.append(carry);
                }
                ans = addStrings(ans, sb.reverse().toString());
                index1--;
            }
            return ans;
        }

        public static String addStrings(String num1, String num2){
            int index1 = num1.length() - 1;
            int index2 = num2.length() - 1;
            int carry = 0;
            StringBuilder sb2 = new StringBuilder();
            while (index1 >= 0 || index2 >= 0){
                int num1_Int = index1 >= 0 ? num1.charAt(index1) - '0' : 0;
                int num2_Int = index2 >= 0 ? num2.charAt(index2) - '0' : 0;
                int temp = num1_Int + num2_Int + carry;
                carry = temp / 10;
                sb2.append(temp % 10);
                index1--;
                index2--;
            }
            if (carry > 0){
                sb2.append(carry);
            }
            return sb2.reverse().toString();
        }

}
